import axios from 'axios';

const API_URL = 'http://localhost:8000/api/';  // 确保后端接口地址正确

const axiosInstance = axios.create({
  baseURL: API_URL,
});

axiosInstance.interceptors.request.use(
  (config) => {
    const accessToken = localStorage.getItem('access');
    if (accessToken) {
      config.headers.Authorization = `Bearer ${accessToken}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 添加防抖机制，避免重复刷新 Token
let isRefreshing = false;
let refreshSubscribers = [];

axiosInstance.interceptors.response.use(
  (response) => {
    return response;
  },
  async (error) => {
    const originalRequest = error.config;
    if (error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;

      try {
        const refreshToken = localStorage.getItem('refresh');
        if (!isRefreshing) {
          isRefreshing = true;
          // 刷新 Token 并清空订阅者
          const refreshResponse = await axios.post(`${API_URL}token/refresh/`, {
            refresh: refreshToken,
          });
          isRefreshing = false;

          const newAccessToken = refreshResponse.data.access;
          localStorage.setItem('access', newAccessToken);

          refreshSubscribers.forEach((callback) => callback(newAccessToken));
          refreshSubscribers = [];
        }

        return new Promise((resolve) => {
          const retryOriginalRequest = (newAccessToken) => {
            originalRequest.headers.Authorization = `Bearer ${newAccessToken}`;
            resolve(axios(originalRequest));
          };
          refreshSubscribers.push(retryOriginalRequest);
        });
      } catch (refreshError) {
        console.error('Token refresh failed:', refreshError);
        logoutUser(); // 清除 tokens 并跳转到登录页面
        return Promise.reject(refreshError);
      }
    }
    return Promise.reject(error);
  }
);

// 用户注册
export const registerUser = (userData) => axiosInstance.post('register/', userData);

// 用户登录
export const loginUser = async (credentials) => {
    try {
        const response = await axios.post(`${API_URL}login/`, credentials, {
            headers: {
                'Content-Type': 'application/json',
            },
        });
        localStorage.setItem('access', response.data.access);
        localStorage.setItem('refresh', response.data.refresh);
        return response;
    } catch (error) {
        throw error.response && error.response.data.detail ? new Error(error.response.data.detail) : error;
    }
};

// 用户退出
export const logoutUser = () => {
  localStorage.removeItem('access');
  localStorage.removeItem('refresh');
  // 后续处理，如跳转到登录页面等
};

// 刷新 Tokens
export const refreshTokens = async () => {
  try {
    const response = await axios.post(`${API_URL}token/refresh/`, {
      refresh: localStorage.getItem('refresh'),
    });
    localStorage.setItem('access', response.data.access);
    return response;
  } catch (error) {
    throw new Error('Failed to refresh tokens');
  }
};

export default axiosInstance;